package com.financing.service;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.financing.controller.user.UserController;
import com.financing.util.Str;
import com.jfinal.plugin.activerecord.SqlPara;

public abstract class BaseService<M> {
	private static final Logger logger = Logger.getLogger(UserController.class);

	/**
	 * 根据URL参数生成where条件
	 */
	public SqlPara buildSql(String table, List<String> searchKey, Map<String, String> params) {
		return this.buildSql("select *", table, searchKey, params, " order by create_time desc");
	}
	
	public SqlPara buildSql(String table, List<String> searchKey, Map<String, String> params, String end) {
		return this.buildSql("select *", table, searchKey, params, end);
	}
	
	public SqlPara buildSql(String select, String table, List<String> searchKey, Map<String, String> params) {
		return this.buildSql(select, table, searchKey, params, " order by create_time desc");
	}
	
	public SqlPara buildSql(String select, String table, List<String> searchKey, Map<String, String> params, String end) {
		SqlPara sqlPara = new SqlPara();
		StringBuffer sql = new StringBuffer();
		sql.append(select+" from "+table+" where 1=1 ");
		for(String s : searchKey){
			String sc = Str.underlineToCamel(s);
			if(params.get(sc+"Start")!=null || params.get(sc+"End")!=null){
				if(params.get(sc+"Start")!=null && Str.nb(params.get(sc+"Start"))){
					sql.append(" and "+s+">=? ");
					sqlPara.addPara(params.get(sc+"Start"));
				}
				if(params.get(sc+"End")!=null && Str.nb(params.get(sc+"End"))){
					sql.append(" and "+s+"<=? ");
					sqlPara.addPara(params.get(sc+"End"));
				} 
			}else if(params.get(sc)!=null && Str.nb(params.get(sc))){
				String vals = params.get(sc);
				if(vals.contains("*")){
					sql.append(" and (1=2");
					for(String v : Str.split(params.get(sc), "*")){
						sql.append(" or "+s+"=? ");
						sqlPara.addPara(v);
					}
					sql.append(") ");
				}else if(vals.contains("$")){
					for(String v : Str.split(params.get(sc), "$")){
						sql.append(" and "+s+"<>? ");
						sqlPara.addPara(v);
					}
				}else if(vals.contains("~")){
					sql.append(" and (");
					for(String v : Str.split(params.get(sc), "~")){
						sql.append(s+" like ? ");
						sqlPara.addPara("%"+v+"%");
					}
					sql.append(") ");
				}else{
					sql.append(" and "+s+"=? "); 
					sqlPara.addPara(params.get(sc));
				}
			}
		}
		sqlPara.setSql(sql.append(end).toString());
		logger.error("sqlPara==="+sqlPara);
		return sqlPara;
	}
}
